package com.kwd.news.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kwd.news.service.LmCmsMobileService;
import com.kwd.news.service.LmCmsPhoneService;
import com.kwd.news.utils.IPUtil;
import com.meirengu.common.RedisClient;
import com.meirengu.common.StatusCode;
import com.meirengu.model.Result;
import com.meirengu.utils.RequestUtil;
import net.ipip.ipdb.City;
import net.ipip.ipdb.CityInfo;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * ${DESCRIPTION}
 *
 * @author Mao
 * @create 2017-12-19 12:27
 */
@Controller
@RequestMapping("ip")
public class IpController extends BaseController {

    Logger logger = LoggerFactory.getLogger(IpController.class);

    @Autowired
    private RedisClient redisClient;


    @RequestMapping(value = "/{appid}", method = RequestMethod.GET)
    @ResponseBody
    public Result ip(HttpServletRequest request,
                     @PathVariable("appid") String appid) {
        try {
            String ip = RequestUtil.getClientIp(request);
            logger.info(ip);
            Map<String, String> ipMap = IPUtil.getConfig(ip);
            if (ipMap == null) {
                logger.error("本地文件中没有此ip:{}", ip);
                String str = queryIP(ip);
                logger.error("ip138查询:{}", str);
                if (str != null) {
                    JSONObject res = JSON.parseObject(str);
                    if (res != null && "ok".equals(res.getString("res"))) {
                        String data = res.getString("data");
                        String[] arr = (data.substring(1, data.length() - 1)).split(",");
                        ipMap = new HashMap<String, String>();
                        ipMap.put("country_name", arr[0]);
                        ipMap.put("region_name", arr[1]);
                        ipMap.put("city_name", arr[2]);
                    }
                }
            }
            String status = redisClient.hget("appstatus", appid);
            ipMap.put("status", status);
            return setResult(StatusCode.OK, ipMap, StatusCode.codeMsgMap.get(StatusCode.OK));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            logger.error(">> MobileController.insert throw exception: {}", e);
            return super.setResult(StatusCode.INTERNAL_SERVER_ERROR, "", StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }
    }


    public static String get(String urlString, String token) {
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setReadTimeout(5 * 1000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("token", token);
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                StringBuilder builder = new StringBuilder();
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(conn.getInputStream(), "utf-8"));
                for (String s = br.readLine(); s != null; s = br
                        .readLine()) {
                    builder.append(s);
                }
                br.close();
                return builder.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String queryIP(String ip) {
        String url = "http://api.ip138.com/query/?ip=" + ip + "&datatype=jsonp";
        String token = "8d37df239e1f84914bc68194458ef348";
        return get(url, token);
    }


}
